package org.example;

import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

@SpringBootApplication
@Controller
public class StarterController {
    @Autowired
    private Producer producer;

    public static void main(String[] args) {
        SpringApplication.run(StarterController.class,args);
    }

    @PostMapping("/login")
    @ResponseBody
    public String login(String name,String password,String code,HttpSession session){
        if(code.equals(session.getAttribute("code"))){
            return "ok";
        }else {
            return "error";
        }
    }

    @GetMapping("/kaptcha")
    public void getKaptcha(HttpServletResponse response, HttpSession session){
        //生成验证码
        String text=producer.createText();
        BufferedImage image=producer.createImage(text);
        //将验证码存入session
        session.setAttribute("kaptcha",text);
        //将图片输出给浏览器
        response.setContentType("image/png");
        try {
            OutputStream os =response.getOutputStream();
            ImageIO.write(image,"png",os);
        } catch (IOException e) {
            System.out.println("响应验证失败"+e.getMessage());
        }

    }
}
